Popular Searches
Popular Course Categories
Popular Courses

Understanding range() and Sequence Iteration

Understanding range() and Sequence Iteration

Loops and Iteration in Python

Understanding range() and Sequence Iteration in Python

Course: Python Programming Training

Topic: Understanding range() and Sequence Iteration

Course Link: Python Training Course – JustAcademy

Demo Registration: Register for a Free Course Demo

Website: JustAcademy Official Website


1. Introduction to range() and Sequence Iteration

Python provides several tools for repeating operations and processing collections of data. Two important concepts are the built-in range() function and sequence iteration. The range() function produces a sequence of integers following a specified pattern, while sequence iteration allows a program to access items from collections such as lists, tuples, strings, and ranges one at a time.

These concepts are commonly used with for loops to repeat tasks, process records, access elements, calculate totals, and perform operations a specific number of times.

For example, if a program needs to display numbers from 0 to 4, you can use range(5) instead of writing five separate print statements.

for number in range(5):
    print(number)

Output:

0
1
2
3
4

The ending value is excluded, so range(5) generates integers from 0 through 4.

2. Learning Objectives

After completing this topic, you should be able to:

  • Explain the purpose of the range() function.
  • Understand the start, stop, and step arguments.
  • Use ranges with for loops.
  • Iterate through strings, lists, tuples, and other sequences.
  • Understand forward and reverse iteration.
  • Use len(), enumerate(), and indexing while iterating.
  • Recognize the difference between an iterable, an iterator, and a sequence.
  • Avoid common errors involving range boundaries and step values.
  • Apply sequence iteration to practical programming problems.

3. What Is the range() Function?

The range() function is a Python built-in function that represents an immutable sequence of integers. It is frequently used when a loop must execute a particular number of times or when numbers need to be generated according to a regular interval.

Unlike a list containing every number, a range object generally stores the information needed to calculate its values rather than creating a list of all those values immediately. This makes it memory-efficient for many counting tasks.

Basic Syntax

range(stop)
range(start, stop)
range(start, stop, step)

The function supports one, two, or three integer arguments.

Argument Meaning Default Example
start The first value in the range, if the range is non-empty. 0 range(3, 8)
stop The boundary where generation stops; this value is excluded. No default range(5)
step The amount added to the current value at each step. 1 range(2, 12, 2)

4. Using range() with One Argument

When one argument is supplied, it represents the stopping value. Python starts at zero and generates integers up to, but not including, that value.

Example 1: Display Numbers from Zero to Four

for i in range(5):
    print(i)

Output:

0
1
2
3
4

Explanation:

  • The start value defaults to 0.
  • The stop value is 5.
  • The step defaults to 1.
  • The values generated are 0, 1, 2, 3, and 4.
  • The number 5 is not included.

Example 2: Repeat an Operation Five Times

for count in range(5):
    print("Python is easy to practice!")

Output:

Python is easy to practice!
Python is easy to practice!
Python is easy to practice!
Python is easy to practice!
Python is easy to practice!

Here, the loop executes five times. The variable count receives the values 0 through 4, even though the program does not display them.

5. Using range() with Two Arguments

When two arguments are supplied, the first specifies the starting value and the second specifies the excluded stopping value.

for number in range(3, 8):
    print(number)

Output:

3
4
5
6
7

Explanation: The loop starts at 3 and increases by 1 until the next value would reach 8. Therefore, 8 is not printed.

Example: Display Numbers from 10 to 15

for number in range(10, 16):
    print(number, end=" ")

Output:

10 11 12 13 14 15

To include 15 in a range with a positive step of 1, use 16 as the stop value.

6. Using range() with Three Arguments

The three-argument form allows you to control the interval between values. The third argument is called the step.

range(start, stop, step)

The step determines how much the current value changes during each iteration.

Example 1: Generate Even Numbers

for number in range(2, 12, 2):
    print(number)

Output:

2
4
6
8
10

The sequence starts at 2, increases by 2, and stops before reaching 12.

Example 2: Generate Numbers with a Step of Three

for number in range(0, 16, 3):
    print(number, end=" ")

Output:

0 3 6 9 12 15

Example 3: Generate Odd Numbers

for number in range(1, 11, 2):
    print(number, end=" ")

Output:

1 3 5 7 9

7. Understanding the Excluded Stop Value

One of the most important rules of range() is that the stop value is excluded. This is often described as a half-open interval: the starting boundary is included when reachable, while the stopping boundary is not.

Expression Generated Values Number of Values
range(5) 0, 1, 2, 3, 4 5
range(1, 5) 1, 2, 3, 4 4
range(2, 10, 2) 2, 4, 6, 8 4
range(5, 5) No values 0
range(8, 3) No values with the default positive step 0

Why Is the Stop Value Excluded?

Excluding the stop value makes ranges useful for indexing. If a list contains five elements, its valid indexes are 0, 1, 2, 3, and 4. Therefore, range(len(my_list)) generates exactly the indexes needed to visit every element.

colors = ["red", "green", "blue"]

for index in range(len(colors)):
    print(index, colors[index])

Output:

0 red
1 green
2 blue

8. Understanding Positive and Negative Steps

A positive step moves the range forward toward larger numbers. A negative step moves it backward toward smaller numbers.

Positive Step

for number in range(1, 6, 1):
    print(number, end=" ")

Output:

1 2 3 4 5

Negative Step: Count Backward

for number in range(5, 0, -1):
    print(number, end=" ")

Output:

5 4 3 2 1

In this example, the starting value is 5, the stop value is 0, and the step is -1. The loop stops before reaching 0.

Example: Countdown

print("Countdown started")

for seconds in range(5, 0, -1):
    print(seconds)

print("Go!")

Output:

Countdown started
5
4
3
2
1
Go!

Important Rule

The direction of the step must be compatible with the start and stop values. A positive step cannot move downward from a larger starting value toward a smaller stop value. Likewise, a negative step cannot move upward toward a larger stop value.

print(list(range(5, 1)))       # []
print(list(range(1, 5, -1)))   # []

Both ranges are empty because their steps do not move toward the stopping boundary.

9. What Is Sequence Iteration?

Sequence iteration means processing elements from an ordered collection one at a time. Python sequences include strings, lists, and tuples. Other iterable objects, such as sets, dictionaries, and file objects, can also be processed using loops, although they do not all behave like ordered sequences in the same way.

The most common way to iterate through a collection is with a for loop.

General Syntax

for item in collection:
    # Perform an operation on item
    print(item)

Python retrieves the next item from the iterable and assigns it to the loop variable. The loop body executes for each item until there are no more items.

10. Iterating Through a List

A list stores multiple values in a single variable. You can use a for loop to process every element without manually accessing each index.

fruits = ["apple", "banana", "mango", "orange"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
mango
orange

In this example, fruit represents the current list element during each iteration.

Calculating the Total of List Values

prices = [100, 250, 150, 300]
total = 0

for price in prices:
    total += price

print("Total:", total)

Output:

Total: 800

Direct iteration is usually clearer than using indexes when you only need each element's value.

11. Iterating Through a Tuple

A tuple is an ordered collection that cannot be modified after creation. It supports iteration in the same way as a list.

coordinates = (10, 20, 30)

for coordinate in coordinates:
    print(coordinate)

Output:

10
20
30

Tuples are useful for fixed collections of values, such as coordinates, RGB color components, or records that should not be changed accidentally.

12. Iterating Through a String

A string is a sequence of characters. A for loop can visit each character individually.

word = "PYTHON"

for character in word:
    print(character)

Output:

P
Y
T
H
O
N

Counting Characters

message = "hello"
count = 0

for character in message:
    count += 1

print("Character count:", count)

Output:

Character count: 5

Python's built-in len(message) is simpler for ordinary length calculations, but this example demonstrates how iteration works.

13. Using range() to Iterate Through Sequence Indexes

Sometimes a program needs an element's position as well as its value. You can combine range() with len() to generate valid indexes.

subjects = ["Python", "SQL", "Power BI"]

for index in range(len(subjects)):
    print(index, subjects[index])

Output:

0 Python
1 SQL
2 Power BI

How it works:

  1. len(subjects) returns 3.
  2. range(3) generates 0, 1, and 2.
  3. The loop assigns each index to index.
  4. subjects[index] retrieves the corresponding element.

When Should You Use Index-Based Iteration?

  • When you need to update elements by position.
  • When comparing neighboring elements.
  • When working with two sequences using matching indexes.
  • When a calculation depends on the position of an item.

If you only need the values, prefer direct iteration such as for subject in subjects:.

14. Using enumerate() to Get Index and Value

The enumerate() function is often a cleaner alternative to combining range() and len(). It produces pairs containing an index and the corresponding value.

languages = ["Python", "Java", "JavaScript"]

for index, language in enumerate(languages):
    print(index, language)

Output:

0 Python
1 Java
2 JavaScript

Starting the Index at One

You can specify a starting counter using the optional start argument.

tasks = ["Install Python", "Learn variables", "Practice loops"]

for number, task in enumerate(tasks, start=1):
    print(number, task)

Output:

1 Install Python
2 Learn variables
3 Practice loops

Use enumerate() when you need both the position and the value of each item.

15. Iterating in Reverse

You can iterate through a sequence in reverse order using the built-in reversed() function. This is useful when you want to process elements from last to first without manually calculating indexes.

numbers = [10, 20, 30, 40]

for number in reversed(numbers):
    print(number)

Output:

40
30
20
10

Reverse Iteration with range()

for number in range(10, 0, -2):
    print(number, end=" ")

Output:

10 8 6 4 2

Use reversed() when you want to traverse an existing reversible sequence backward. Use a negative-step range when you want to generate a descending numerical sequence.

16. Iterating Through Dictionaries

A dictionary stores key-value pairs. By default, iterating directly over a dictionary produces its keys.

Iterating Over Keys

student = {
    "name": "Aarav",
    "course": "Python",
    "score": 90
}

for key in student:
    print(key)

Output:

name
course
score

Iterating Over Values

for value in student.values():
    print(value)

Output:

Aarav
Python
90

Iterating Over Keys and Values

for key, value in student.items():
    print(key, ":", value)

Output:

name : Aarav
course : Python
score : 90

Dictionary iteration follows insertion order in modern Python. However, dictionaries are mappings rather than sequences indexed by numeric positions.

17. Iterating Through a Set

A set stores unique elements. You can iterate over its elements with a for loop, but you should not depend on a particular iteration order.

skills = {"Python", "SQL", "Excel"}

for skill in skills:
    print(skill)

The output contains the three skills, but their order is not guaranteed to match the order in which they were written.

If predictable sorted output is required, use sorted():

for skill in sorted(skills):
    print(skill)

Output:

Excel
Python
SQL

18. Understanding range Objects

Calling range() does not normally create and display a list of numbers. Instead, it returns a range object that represents the sequence.

numbers = range(5)
print(numbers)
print(list(numbers))

Output:

range(0, 5)
[0, 1, 2, 3, 4]

The first output shows the range object's representation. The second converts the range into a list so that all its values can be displayed together.

Useful Properties of range Objects

  • They represent immutable integer sequences.
  • They support iteration, indexing, and slicing.
  • They can be checked for membership with the in operator.
  • They use little memory compared with storing every generated number in a list.
  • They require integer-compatible arguments.

Example: Indexing and Membership

numbers = range(2, 12, 2)

print(numbers[0])
print(numbers[2])
print(8 in numbers)
print(7 in numbers)

Output:

2
6
True
False

19. Converting a Range into a List or Tuple

Although range objects are iterable, sometimes you need an actual list or tuple for display, storage, or further processing.

numbers = range(1, 6)

number_list = list(numbers)
number_tuple = tuple(numbers)

print(number_list)
print(number_tuple)

Output:

[1, 2, 3, 4, 5]
(1, 2, 3, 4, 5)

Be careful when converting very large ranges into lists or tuples. The conversion creates a collection containing all the values, which requires memory proportional to the number of elements.

20. Using range() for Mathematical Calculations

Ranges are useful for generating numbers used in sums, multiplication tables, averages, and other mathematical operations.

Example 1: Sum of Numbers

total = 0

for number in range(1, 6):
    total += number

print("Sum:", total)

Output:

Sum: 15

Example 2: Multiplication Table

number = 7

for multiplier in range(1, 11):
    print(number, "x", multiplier, "=", number * multiplier)

Sample Output:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70

Example 3: Calculate a Factorial

number = 5
factorial = 1

for value in range(1, number + 1):
    factorial *= value

print("Factorial:", factorial)

Output:

Factorial: 120

The expression number + 1 is used because the stop value is excluded. For the input 5, the loop must include 5 in the calculation.

21. Combining range() with Conditional Statements

You can use an if statement inside a loop to process only values that meet a condition.

Example: Find Even Numbers

for number in range(1, 11):
    if number % 2 == 0:
        print(number)

Output:

2
4
6
8
10

Example: Separate Even and Odd Numbers

for number in range(1, 6):
    if number % 2 == 0:
        print(number, "is even")
    else:
        print(number, "is odd")

Output:

1 is odd
2 is even
3 is odd
4 is even
5 is odd

22. Using break and continue During Iteration

The break and continue statements change the normal flow of a loop.

The break Statement

break immediately terminates the innermost enclosing loop.

for number in range(1, 10):
    if number == 5:
        break
    print(number)

Output:

1
2
3
4

The continue Statement

continue skips the remaining statements in the current iteration and moves to the next value.

for number in range(1, 6):
    if number == 3:
        continue
    print(number)

Output:

1
2
4
5

Use these statements when they make the intended loop behavior clearer. Avoid unnecessarily complicated control flow.

23. Nested Loops and Sequence Iteration

A nested loop is a loop placed inside another loop. Each iteration of the outer loop runs the inner loop to completion unless control flow interrupts it.

Example: Display a Grid of Coordinates

for row in range(1, 4):
    for column in range(1, 3):
        print("Row:", row, "Column:", column)

Output:

Row: 1 Column: 1
Row: 1 Column: 2
Row: 2 Column: 1
Row: 2 Column: 2
Row: 3 Column: 1
Row: 3 Column: 2

The outer loop runs three times, and the inner loop runs twice for every outer iteration. Therefore, the inner statement executes six times.

Example: Print a Star Pattern

for row in range(1, 5):
    for column in range(row):
        print("*", end="")
    print()

Output:

*
**
***
****

24. Understanding Iterable, Iterator, and Sequence

These terms are related but have different meanings in Python.

Concept Meaning Examples
Iterable An object from which Python can obtain items one at a time. List, tuple, string, range, set, dictionary
Iterator An object that provides successive values through the iterator protocol. An iterator created using iter()
Sequence An ordered collection that supports positional access and sequence operations. List, tuple, string, range
Range object An immutable sequence representing a regular progression of integers. range(1, 10, 2)

Example: Creating an Iterator

numbers = [10, 20, 30]
iterator = iter(numbers)

print(next(iterator))
print(next(iterator))
print(next(iterator))

Output:

10
20
30

The iter() function obtains an iterator from an iterable, and next() retrieves the next item. Calling next() after all items have been consumed raises StopIteration, unless a default value is provided.

25. Using zip() to Iterate Through Multiple Sequences

When two or more sequences need to be processed together, zip() combines their corresponding elements into tuples.

names = ["Aarav", "Diya", "Kabir"]
scores = [85, 92, 78]

for name, score in zip(names, scores):
    print(name, "scored", score)

Output:

Aarav scored 85
Diya scored 92
Kabir scored 78

By default, zip() stops when the shortest input iterable is exhausted. Use it when values correspond by position and you want to process them together without manually managing indexes.

26. Common Errors When Using range()

Error or Mistake Why It Happens Correction
Expecting the stop value to appear The stop boundary is excluded. Use an appropriate stop value, such as range(1, 6) to include 5.
Using a zero step A range cannot advance by zero. Use a non-zero integer step.
Using the wrong step direction The range cannot move toward its stop boundary. Use a positive step to move upward or a negative step to move downward.
Passing a float range() expects integer-compatible arguments. Use integer arguments or another approach for decimal intervals.
Accessing an invalid index The index is outside the sequence's valid range. Use range(len(sequence)) when index iteration is required.
Converting an enormous range into a list The list stores all generated values in memory. Iterate over the range directly if a list is unnecessary.
Using indexes when values are enough The loop becomes more complicated than necessary. Prefer direct iteration or enumerate().

Error Example: Zero Step

numbers = range(1, 10, 0)

This raises ValueError because the step cannot be zero.

Error Example: Float Arguments

# This raises TypeError:
# range(1.5, 5.5)

For decimal sequences, consider a loop with a suitable numeric calculation or a library designed for numerical data.

27. Best Practices for Range and Sequence Iteration

  • Use range(stop) when you need to repeat an operation a known number of times.
  • Remember that the stop value is excluded.
  • Choose a step that moves toward the stop boundary.
  • Use direct iteration when you only need the elements of a collection.
  • Use enumerate() when both an index and its value are needed.
  • Use zip() to process corresponding elements from multiple iterables.
  • Use reversed() for reverse traversal of a reversible sequence.
  • Avoid changing a collection's size while iterating directly over it; use a copy or build a new collection when necessary.
  • Do not convert a range to a list unless the list is actually needed.
  • Use descriptive loop variable names, such as student, score, or index.
  • Keep nested loops simple and consider their total number of iterations when processing large datasets.

28. Practical Project: Student Score Analyzer

This mini-project uses range(), sequence iteration, indexing, and conditional statements to analyze student scores.

Project Requirements

  • Store student names and scores in lists.
  • Display each student's name and score.
  • Calculate the total and average score.
  • Identify whether each student passed or failed.
  • Display the highest score.

Program

students = ["Aarav", "Diya", "Kabir", "Meera"]
scores = [85, 92, 48, 76]

total = 0

print("STUDENT SCORE REPORT")
print("--------------------")

for index in range(len(students)):
    name = students[index]
    score = scores[index]
    total += score

    if score >= 50:
        result = "Pass"
    else:
        result = "Fail"

    print(name, "-", score, "-", result)

average = total / len(scores)
highest_score = max(scores)

print("--------------------")
print("Total Score:", total)
print("Average Score:", round(average, 2))
print("Highest Score:", highest_score)

Expected Output

STUDENT SCORE REPORT
--------------------
Aarav - 85 - Pass
Diya - 92 - Pass
Kabir - 48 - Fail
Meera - 76 - Pass
--------------------
Total Score: 301
Average Score: 75.25
Highest Score: 92

Alternative Using zip()

Because the names and scores correspond by position, zip() provides a more direct way to process both lists together.

students = ["Aarav", "Diya", "Kabir", "Meera"]
scores = [85, 92, 48, 76]

for student, score in zip(students, scores):
    status = "Pass" if score >= 50 else "Fail"
    print(f"{student}: {score} - {status}")

This alternative avoids manually accessing the lists by index. The two lists should contain matching numbers of entries if every student must have a corresponding score.

29. Practice Exercises

  1. Write a program to print numbers from 1 to 20 using range().
  2. Print all even numbers between 2 and 50.
  3. Display numbers from 20 down to 1 using a negative step.
  4. Calculate the sum of integers from 1 to 100.
  5. Print the multiplication table of a number entered by the user.
  6. Iterate through a string and count how many vowels it contains.
  7. Display each element of a list alongside its index using enumerate().
  8. Iterate through two lists of names and marks using zip().
  9. Print the elements of a list in reverse order.
  10. Create a program that counts how many values in a list are greater than 50.
  11. Generate a right-angled triangle pattern using nested loops and range().
  12. Build a student report that calculates the total, average, highest mark, and pass/fail result.

30. Interview Questions and Answers

Q1. What is range() in Python?

Answer: range() is a built-in function that returns an immutable sequence of integers. It is commonly used to control the number of iterations in a loop.

Q2. What are the three arguments of range()?

Answer: start determines the beginning, stop determines the excluded boundary, and step determines the interval between values.

Q3. What does range(5) generate?

Answer: It represents the values 0, 1, 2, 3, and 4.

Q4. Is the stop value included in range()?

Answer: No. The stop value is excluded from the generated sequence.

Q5. Can range() generate numbers in reverse order?

Answer: Yes. A negative step can generate descending values, as in range(5, 0, -1).

Q6. What happens when the step is zero?

Answer: Python raises a ValueError because a range cannot advance with a zero step.

Q7. What is sequence iteration?

Answer: Sequence iteration is the process of accessing and processing the elements of a sequence one at a time, usually through a loop.

Q8. What is the difference between range() and a list?

Answer: A list stores its elements, whereas a range represents a regular sequence of integers without normally storing each value separately.

Q9. How do you get both an index and a value during iteration?

Answer: Use enumerate(), for example, for index, value in enumerate(items):.

Q10. What is the purpose of len() with range()?

Answer: len() returns the number of elements in a collection. Combining it with range() can generate valid indexes for that collection.

Q11. What is the difference between an iterable and an iterator?

Answer: An iterable can provide an iterator. An iterator maintains iteration state and returns successive values through operations such as next().

Q12. How can you iterate over two lists together?

Answer: Use zip() to retrieve corresponding values from both lists in each iteration.

Q13. What happens when range(5, 5) is used?

Answer: It produces an empty range because the starting value is already at the excluded stop boundary.

Q14. Can range() accept floating-point numbers?

Answer: No. Its arguments must be integers or objects that support the integer index protocol.

Q15. When should direct iteration be preferred over range(len())?

Answer: Direct iteration is preferable when only the elements are needed. Use range(len()) when indexes are genuinely required.

31. Quick Revision Checklist

  • range(5) generates 0 through 4.
  • range(2, 6) generates 2 through 5.
  • range(2, 12, 2) generates even numbers from 2 through 10.
  • range(5, 0, -1) generates 5 through 1.
  • The stop value is excluded.
  • The step must not be zero.
  • Use a negative step for descending ranges.
  • Use direct iteration to process collection values.
  • Use enumerate() to access indexes and values together.
  • Use zip() to iterate through multiple collections in parallel.
  • A range object is iterable, immutable, and memory-efficient.
  • Use list(range(...)) when an actual list of generated numbers is required.

32. Conclusion

The range() function and sequence iteration are essential parts of Python programming. The range function generates predictable integer sequences for loops, while iteration makes it possible to process collection elements efficiently. Understanding the start, stop, and step arguments helps prevent off-by-one errors and makes loop behavior easier to predict.

Practice iterating over lists, tuples, strings, dictionaries, and ranges. Learn when to use indexes, enumerate(), zip(), and reversed() so that your programs remain readable and efficient. These skills provide a foundation for more advanced topics such as comprehensions, iterators, generators, data processing, and algorithm development.


Continue Learning with JustAcademy

Explore the Python training course for additional lessons, practical exercises, and programming concepts.

whatsapp